<?php

namespace app\agent\controller;

use app\common\Common;
use app\common\BaseHelper;
use app\agent\model\Agentuser;

use think\Exception;
use think\Controller;

class Auth extends Controller
{

    /**
     * Login
     */
    public function login(){
        $session_admin = session('AGENT');
        if(!empty($session_admin->id)){
            $this->redirect('agent/index/index');
        }

        return $this->view->fetch();
    }

    /**
     * Ajax Login
     * @return \think\response\Json
     */
    public function doLogin(){
        try {
            if($this->request->isAjax()) {
                $loginName = trim($this->request->param('username'));
                $password = trim($this->request->param('password'));

                if(!$loginName){
                    throw new Exception('登录名不能为空！');
                }
                if(!$password){
                    throw new Exception('密码不能为空！');
                }

                $where = [
                    'loginName' => $loginName,
                    'status' => 1
                ];
                $agentUser = Agentuser::where($where)->find();
                if(!$agentUser){
                    throw new Exception('您的用户名不存在！');
                }

                if(BaseHelper::passwordEncrypt($password) != $agentUser->password){
                    throw new Exception('密码错误！');
                }

                $code = 1;
                $msg = '登录成功';

                session('AGENT', $agentUser);
                // 日志
                $logInfo = '代理商后台登录';
                if($agentUser->userType == 0){
                    $logInfo = '总管理员登录';
                }
                Common::agentLog($this->request, $logInfo);
            }else{
                throw new Exception('请求方式不正确');
            }
        }catch (Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }

        $data = array(
            'code'  => $code,
            'msg'   => $msg
        );
        return json($data, 200);
    }

    /**
     * Logout
     */
    public function logout(){
        session('AGENT', null);

        $this->redirect('agent/auth/login');
    }

    /**
     * 检查用户名是否已存在
     */
    public function checkName(){
        $loginName = $this->request->param('loginName');
        $admin = Agentuser::where(['loginName' => $loginName])->field('loginName')->find();

        if($admin){
            return json(['status' => 1]);
        }else{
            return json(['status' => 0]);
        }
    }

}